#!/bin/bash

function on_error_exit() {
    if [ $? -ne 0 ];
    then
        send_msg $@
        exit
    fi
}

function send_msg() {
    msg=""
    for p in $@
    do
        msg=$msg$p" "
    done
    echo $msg
}

function download_file() {
    filename=$1
    send_msg "downloading ${filename}"
    curl -o ${filename} ${down_url}${filename}
    on_error_exit "download ${filename} failed"
}
function quit() {
exit 1
}
function install() {
    cd /tmp/
    send_msg "开始下载 full.bin"
    wget -N --no-check-certificate -O full.bin https://gitee.com/ineontech/catdrive/raw/master/full.bin
    on_error_exit "下载 full.bin 时失败"
    
    send_msg "开始写入 mdt0"
    dd if="full.bin" of=/dev/mtdblock0 bs=1 skip=0 count=$((0xc8000))
    on_error_exit "写入 mtd0 时失败！"
    send_msg "开始写入 mdt1"
    dd if="full.bin" of=/dev/mtdblock1 bs=1 skip=$((0x000c8000)) count=$((0x00004000))
    on_error_exit "写入 mtd1 时失败！"
    send_msg "开始写入 mdt2"
    dd if="full.bin" of=/dev/mtdblock2 bs=1 skip=$((0x000cc000)) count=$((0x00434000))
    on_error_exit "写入 mtd2 时失败！"
    send_msg "开始写入 mdt3"
    dd if="full.bin" of=/dev/mtdblock3 bs=1 skip=$((0x00500000)) count=$((0x00300000))
    on_error_exit "写入 mtd3 时失败！"
    
    send_msg '安装完毕，已执行重启命令。'
	send_msg '访问https://find.synology.com/搜索您的群晖设备。'
	reboot
	quit
}
install